<template>
  <div>
    <window
      :show="windowConfig.show"
      :buttons="windowConfig.buttons"
      @close="closeWindow"
    >
      <el-form :model="formData" :rules="rules1" ref="formDataRef">
        <el-form-item prop="title">
          <div class="title-input">
            <el-input
              placeholder="请输入博客标题"
              v-model.trim="formData.title"
              size="large"
            >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="content">
          <div class="markdownContent" :style="{ width: '100%' }">
            <EditorHtml
              v-if="formData.editorType === 0"
              :height="editorHtmlHeight"
              v-model="formData.content"
              >{{ formData.editorType }}</EditorHtml
            >
            <EditorMarkdown
              v-else
              :height="editorMarkdownHeight"
              v-model="formData.markdownContent"
              @htmlContent="setHtmlContent"
            ></EditorMarkdown>
          </div>
        </el-form-item>
      </el-form>

      <Dialog
        :show="dialogConfig.show"
        :title="dialogConfig.title"
        :buttons="dialogConfig.buttons"
        @close="dialogConfig.show = false"
        width="800px"
        ><el-form
          :model="formData"
          :rules="rules2"
          ref="formDataRef"
          label-width="70px"
          label-position="top"
          class="blog-setting-form"
        >
          <el-form-item prop="categoryId" label="分类 ">
            <el-select
              v-model.trim="formData.categoryId"
              placeholder="请选择博客分类"
              clearable
            >
              <el-option :value="0" label="全部分类"></el-option>
              <el-option
                :value="item.categoryId"
                :label="item.categoryName"
                v-for="item in categoryList"
                :key="item.categoryId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="cover" label="封面 ">
            <CoverUpload v-model="formData.cover"></CoverUpload>
          </el-form-item>
          <el-form-item prop="type" label="类型 ">
            <el-radio-group v-model="formData.type">
              <el-radio :value="0">原创</el-radio>
              <el-radio :value="1">转载</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            prop="reprintUrl"
            label="原文地址 "
            v-if="formData.type == 1"
          >
            <el-input
              placeholder="请输入原文地址"
              v-model.trim="formData.reprintUrl"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="allowComment" label="允许评论 ">
            <dic class="allow-comment">
              <el-radio-group v-model="formData.allowComment">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</el-radio>
              </el-radio-group>
              <span class="info"
                >请先在评论设置里设置好相应参数，评论才会生效</span
              >
            </dic>
          </el-form-item>
          <el-form-item prop="summary" label="简介 ">
            <el-input
              placeholder="请输入分类介绍"
              v-model.trim="formData.summary"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 4 }"
              size="large"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="categoryDesc" label="博客标签 ">
            <div class="tag-input-panel">
              <div class="tag-list">
                <el-tag
                  v-for="(item, index) in formData.tag"
                  @close="closeTag(index)"
                  :key="item"
                  class="tag-item"
                  closable
                >
                  {{ item }}
                </el-tag>
              </div>

              <span class="info" v-if="formData.tag.length == 0"
                >添加标签更容易被搜索引擎收录</span
              >
              <span
                class="iconfont icon-add"
                @click="showTagInputHandler"
                v-if="!showTagInput"
              ></span>
              <el-input
                ref="inputRef"
                class="tag-input"
                v-if="showTagInput"
                v-model.trim="tagInputValue"
                @blur="tagInputResult"
                v-on:keyup.enter="handleEnterKey"
              ></el-input>
            </div>
          </el-form-item> </el-form
      ></Dialog>

      <!-- <EditorMarkdown :height="editorMarkdownHeight"></EditorMarkdown> -->
      <!-- <EditorHtml :height="editorHtmlHeight"></EditorHtml> -->
    </window>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getCurrentInstance,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref,
} from "vue";
// <EditorMarkdown :height="editorHeight"></EditorMarkdown>
const { proxy } = getCurrentInstance();

const api = {
  loadCategoryList: "/category/loadAllCategory4Blog",
  saveCategory: "category/saveCategory4Blog",
  delCategory: "/category/delCategory4Blog",
  changeSort: "/category/changeCategorySort4Blog",
  saveBlog: "blog/saveBlog",
  getUserInfo: "getUserInfo",
  getBlogDetail: "/blog/getBlogById",
  autoSave: "blog/autoSaveBlog",
};

const init = (type, data) => {
  windowConfig.show = true;
  // console.log(data);
  nextTick(() => {
    formDataRef.value.resetFields();
    formData.value = { tag: [] };
    startTimer();
    if (type === "add") {
      getUserInfo();
    } else {
      getBlogDetail(data.blogId);
    }
  });
};

defineExpose({ init });

// 自动保存

let timer = ref(null);

const startTimer = () => {
  timer.value = setInterval(() => {
    autoSave();
  }, 5000);
};

const cleanTimer = () => {
  if (timer.value !== null) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

const autoSave = async () => {
  console.log(formData.value.content);
  console.log(formData.value.markdownContent);
  if (
    (formData.value.title === "" && formData.value.content === "<p><br></p>") ||
    (formData.value.title === "" && formData.value.content === "") ||
    dialogConfig.show === true ||
    timer.value === null
  ) {
    return;
  }
  const params = {};
  Object.assign(params, formData.value);
  let result = await proxy.Request({
    url: api.autoSave,
    params: params,
  });
  if (!result) {
    return;
  }
  formData.value.blogId = result.data;
};

const getUserInfo = async () => {
  let result = await proxy.Request({
    url: api.getUserInfo,
  });
  if (!result) {
    return;
  }
  formData.value.editorType = result.data.editorType;
};
// 编辑器的高度
const editorMarkdownHeight =
  window.innerHeight - 60 - 20 - 30 - 50 - 10 - 30 - 65;
const editorHtmlHeight = window.innerHeight - 290 - 65;

const formDataRef = ref(null);
const formData = ref({ tag: [] });
const rules1 = {
  title: [{ required: true, message: "请输入博客标题" }],
  content: [{ required: true, message: "请输入博客内容" }],
};
const rules2 = {
  categoryId: [{ required: true, message: "请选择博客分类" }],
  type: [{ required: true, message: "请选择博客类型" }],
  allowComment: [{ required: true, message: "请选择是否允许评论" }],
  reprintUrl: [{ required: true, message: "请输入原文地址" }],
};

//博客分类
const categoryList = ref([]);
const loadCategoryList = async () => {
  let result = await proxy.Request({
    url: api.loadCategoryList,
  });
  if (!result) {
    return;
  }
  categoryList.value = result.data;
};
onMounted(() => {
  loadCategoryList();
});
onUnmounted(() => {
  cleanTimer();
});

// 博客类型
const radio1 = ref("1");

const dialogConfig = reactive({
  show: false,
  title: "博客设置",
  buttons: [
    {
      type: "danger",
      text: "确定",
      click: (e) => {
        submitBlog();
      },
    },
  ],
});
// window 新增，取消

const windowConfig = reactive({
  show: false,
  title: "标题",
  buttons: [
    {
      type: "danger",
      text: "确定",
      click: (e) => {
        showSettings();
      },
    },
  ],
});

// 关闭编辑博客的界面并刷新
const emit = defineEmits();
const closeWindow = () => {
  windowConfig.show = false;
  emit("callback");
  if (timer.value !== null) {
    cleanTimer();
  }
};

// 修改或新增博客
const showEditBlog = (type, data) => {
  windowConfig.show = true;
};

// 显示提交博客的设置dialog
const showSettings = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    dialogConfig.show = true;
  });
};

// 博客标签
const closeTag = (index) => {
  formData.value.tag.splice(index, 1);
};
const showTagInput = ref(false);
const showTagInputHandler = () => {
  showTagInput.value = true;
};
const tagInputValue = ref(null);
const tagInputResult = () => {
  if (tagInputValue.value == undefined || tagInputValue.value == "") {
    // ElMessage.info("请输入标签内容");
    showTagInput.value = false;
    return;
  }
  if (formData.value.tag.indexOf(tagInputValue.value) !== -1) {
    tagInputValue.value = undefined;
    ElMessage.info("已经添加过该标签了，请重新输入");
    return;
  }
  showTagInput.value = false;
  formData.value.tag.push(tagInputValue.value);
  tagInputValue.value = undefined;
};
const inputRef = ref(null);
const handleEnterKey = () => {
  inputRef.value.blur();
};

const submitBlog = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    const params = {};
    Object.assign(params, formData.value);
    params.tag = params.tag.join("|");
    let result = await proxy.Request({
      url: api.saveBlog,
      params: params,
    });
    if (!result) {
      return;
    }
    ElMessage.success("保存博客成功！");
    dialogConfig.show = false;
    closeWindow();
  });
};

const getBlogDetail = async (blogId) => {
  let result = await proxy.Request({
    url: api.getBlogDetail,
    params: {
      blogId: blogId,
    },
  });
  if (!result) {
    return;
  }
  // console.log(result.data);
  formData.value = result.data;
  if (result.data.tag) {
    formData.value.tag = result.data.tag.split("|");
  } else {
    formData.value.tag = [];
  }

  console.log(formData.value.tag);
};

// markdown编辑器设置html内容
const setHtmlContent = (htmlContent) => {
  formData.value.content = htmlContent;
};
</script>

<style lang="scss" scoped>
.title-input {
  width: 100%;
  border-bottom: 1px solid #ddd;
}
.title-input :deep(.el-input__wrapper) {
  background-color: #ffffff;
  box-shadow: 0 0 0 0;
  font-size: 18px;
}

.blog-setting-form {
  .allow-comment {
    display: flex;
    .info {
      margin-left: 10px;
      color: #aba9a9;
      font-size: 13px;
    }
  }

  .tag-input-panel {
    display: flex;
    text-align: center;
    .tag-list {
      .tag-item {
        margin-right: 7px;
      }
    }
    .info {
      color: #aba9a9;
      margin-right: 10px;
      font-size: 13px;
    }
    .icon-add {
      color: red;
      margin-right: 10px;
      cursor: pointer;
    }
    .tag-input {
      width: 100px;
    }
  }
}
</style>
